L2-033 简单计算器

题目 L2-033 简单计算器

image-d3d6c627

思路分析

image-ecd03617

代码实现

#include <bits/stdc++.h>

using namespace std;

#define endl '\n'

#define int long long

using ll = long long;

using ull = unsigned long long;

using PII = pair<int, int>;

using Pll = pair<ll, ll>;

int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };

const int inf = 0x3f3f3f3f;

stack<int> s1;

stack<char> s2;

bool error=false;

int calc(int n2,int n1,char op){

	int ans;

	if(op=='+')	ans=n2+n1;

	else if(op=='-')	ans=n2-n1;

	else if(op=='*')	ans=n2*n1;

	else if(op=='/'){

		if(n1==0){

			cout<<"ERROR: "<<n2<<"/"<<n1;

			error=true;

		}else{

			ans=n2/n1;

		}

	}

	return ans;

}

signed main(){

    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    int n;cin>>n;

    for(int i=0;i<n;i++){

    	int tmp;cin>>tmp;

    	s1.push(tmp);

	}

	for(int i=0;i<n-1;i++){

		char op;cin>>op;

		s2.push(op);

	}

	int ans;

	while(!s1.empty() && !s2.empty()){

		int a=s1.top();s1.pop();

		int b=s1.top();s1.pop();

		char op = s2.top();s2.pop();

		ans=calc(b,a,op);

		if(error)	return 0;

		s1.push(ans);

	}

	cout<<ans;

    return 0;

}

同类题型

视频讲解


⬅️ L2-032 彩虹瓶 🏠 00-天梯赛 ➡️ L2-034 口罩发放